<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>

      </div>

    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- 使用自定义指令控制按钮的显示  v-has-roles="['system:role:add']"-->
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"

        >删除
        </el-button>
      </el-col>

    </el-row>
    <!--表格-->
    <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="任务编号" align="center" prop="id"/>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="jobName"
                       label="任务名称"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="beanName"
                       label="Bean名称"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="methodName"
                       label="执行方法"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="params"
                       label="参数"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="cronExpression"
                       label="cron表达式"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="pause" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isPause ? 'warning' : 'success'">{{ scope.row.isPause ? '已暂停' : '运行中' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" :show-overflow-tooltip="true" prop="remark" label="描述"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" prop="createTime" label="创建日期">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-caret-right" size="mini" @click="execute(scope.row)">执行
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-caret-right"
                     @click="updateStatus(scope.row.id,scope.row.isPause ? '恢复' : '暂停')">
            {{ scope.row.isPause ? '恢复' : '暂停' }}
          </el-button>
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--Form表单-->
    <el-dialog :title="title"
               :visible.sync="open"
               :before-close="handleClose" width="750px">

      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="form.jobName" placeholder="请输入任务名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务描述" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入任务描述"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Bean名称" prop="beanName">
              <el-input v-model="form.beanName" placeholder="javaBean名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="执行方法" prop="methodName">
              <el-input v-model="form.methodName" placeholder="执行方法名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="Cron表达式" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式"/>
            </el-form-item>
          </el-col>
          <!--任务负责人-->
          <el-col :span="12">
            <el-form-item label="任务负责人" prop="personInCharge">
              <el-input v-model="form.personInCharge" placeholder="请输入任务负责人"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="告警邮箱" prop="email">
              <el-input v-model="form.email" placeholder="多个邮箱用逗号分开"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="失败后暂停" prop="pauseAfterFailure">
              <el-radio-group v-model="form.pauseAfterFailure" size="mini">
                <el-radio :label="false">是</el-radio>
                <el-radio :label="true">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="任务状态">
              <el-radio-group v-model="form.isPause" size="mini">
                <el-radio :label="false">启用</el-radio>
                <el-radio :label="true">暂停</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数内容">
              <el-input v-model="form.params" rows="3" type="textarea" placeholder="请输入参数内容,多个参数用,分开。目前仅支持基本类型"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确认</el-button>
      </div>
    </el-dialog>

    <!--分页-->
    <el-pagination align="right" style="margin-top: 15px"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="jobQueryParams.page"
                   :page-sizes="[10, 20, 30, 40]"
                   :page-size="jobQueryParams.size"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="totalElements">
    </el-pagination>

  </div>
</template>

<script>
import {listQuartzJobs, del, delIds, updateIsPause, execution, add, edit, getJob} from '@/api/timing'


export default {
  name: 'index',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      delLoading: false,
      tableData: [],
      dialogVisible: false,
      form: {
        jobId: '',
        jobName: '',
        beanName: '',
        methodName: '',
        params: '',
        cronExpression: '',
        personInCharge: '',
        email: '',
        pauseAfterFailure: false,
        isPause: false,
        remark: ''
      },

      jobQueryParams: {
        // 默认的页码
        page: 0,
        // 默认每页数据量
        size: 10,

      },

      // 总共有多少页
      totalPages: 0,
      // 默认数据总数
      totalElements: 10,
      currentPage: 1,
      rules: {
        jobName: [
          {required: true, message: '请输入任务名称', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入任务描述', trigger: 'blur'}
        ],
        beanName: [
          {required: true, message: '请输入Bean名称', trigger: 'blur'}
        ],
        methodName: [
          {required: true, message: '请输入方法名称', trigger: 'blur'}
        ],
        cronExpression: [
          {required: true, message: '请输入Cron表达式', trigger: 'blur'}
        ]
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加任务'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      let that = this
      const jobId = row.id || this.ids
      getJob(jobId).then(response => {
        const {data} = response;
        that.form = data
        that.open = true
        that.title = '修改任务'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let that = this
      const jobIds = row.jobId || this.ids
      this.$confirm('是否确认删除定时任务编号为"' + jobIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delIds(jobIds)
      }).then(() => {
        this.loadData()
        that.$message({showClose: true, message: '删除成功', type: 'success'})
      }).catch(function () {
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        jobId: '',
        jobName: '',
        beanName: '',
        methodName: '',
        params: '',
        cronExpression: '',
        pauseAfterFailure: false,
        isPause: false,
        remark: ''
      }
      this.resetForm('form')
    },
    /** 初始化数据 */
    loadData() {
      let that = this
      listQuartzJobs(this.jobQueryParams)
        .then(function (response) {
          const {data} = response
          that.totalElements = data.totalElements;
          that.tableData = data.content
          that.loading = false
        })
        .catch(function (error) {

        })
    },
    /** 每页显示数据量变更  */
    handleSizeChange: function (val) {
      this.size = val
      this.loadData()
    },
    /**每页显示数据量变更**/
    handleCurrentChange: function (val) {
      this.page = val
      this.loadData()
    },
    /** 表单提交  */
    submitForm(formName) {
      let that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id !== undefined) {
            edit(this.form).then(res => {

              that.$message({showClose: true, message: '修改成功', type: 'success'})
              that.reset()
              that.open = false
              that.loadData()
            }).catch(error => {
                that.$message({showClose: true, message: '修改失败', type: 'error'})
              }
            )
          } else {
            add(this.form).then(res => {
              that.$message({showClose: true, message: '新增成功', type: 'success'})
              that.reset()
              that.open = false
              that.loadData()
            }).catch(error => {
                that.$message({showClose: true, message: '新增失败', type: 'error'})
              }
            )
          }


        } else {

          return false
        }
      })
    },
    handleClose(done) {
      done()
    },

    /**
     * 任务立即执行一次
     * */
    execute(row) {
      let that = this
      this.$confirm('确认要立即执行一次"' + row.jobName + '"任务吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        execution(row.id).then(res => {
          that.$message({showClose: true, message: '执行成功', type: 'success'})
        }).catch(error => {
          that.$message({showClose: true, message: '取消执行', type: 'info'})
        })
      })

    },

    /**
     * 改变状态
     */
    updateStatus(id, status) {
      let that = this
      updateIsPause(id).then(res => {
        that.$message({showClose: true, message: '恢复成功', type: 'success'})
        this.loadData()
      }).catch(error => {
        that.$message({showClose: true, message: '恢复失败', type: 'error'})
      })
    },
    /**
     * 解析时间
     */
    parseTime(time, cFormat) {
      if (arguments.length === 0) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'undefined' || time === null || time === 'null') {
        return ''
      } else if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
          return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    }
  }
}
</script>

<style scoped>


</style>
